/**
 * 
 */
package com.bda.mediatheque.controller;


import com.bda.mediatheque.entities.Adresse;
import com.bda.mediatheque.entities.Panier;
import com.bda.mediatheque.entities.Utilisateur;
import com.bda.mediatheque.service.IPanierDao;
import com.bda.mediatheque.service.IUtilisateurDao;
import com.bda.mediatheque.service.ImplAdresseDao;
import com.bda.mediatheque.service.ImplPanierDao;
import com.bda.mediatheque.service.ImplUtilisateurDao;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;



/**
 * The sevelet class to insert User into database
 */
@WebServlet(name="CreateUserServlet", urlPatterns={"/CreateUser"})
public class CreateUserServlet extends HttpServlet {
    
  

    
    /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException {
        
        String forwardStatement = "SignIn.jsp";
        try 
        {
            String login   = (String) request.getParameter("login");
            // Test if the user exits
            IUtilisateurDao utilisateurDao = new ImplUtilisateurDao();
            Utilisateur loggedUser = utilisateurDao.findUserByLogin(login);
            
            if (null == loggedUser)
            {
                //Get the data from user's form
                String firstName  = (String) request.getParameter("firstName");
                String lastName   = (String) request.getParameter("lastName");
                String dateNaissance   = (String) request.getParameter("dateNaissance");

                String pwd   = (String) request.getParameter("pwd");
                String rue   = (String) request.getParameter("rue");
                String ville   = (String) request.getParameter("ville");
                String codePostal   = (String) request.getParameter("codePostal");

                // Create adress instance
                Adresse userAdress = new Adresse();
                userAdress.setRue(rue);
                userAdress.setVille(ville);
                userAdress.setCodePostal(codePostal);

                // Create user instance
                Utilisateur user = new Utilisateur();
                user.setNom(lastName);
                user.setPrenom(firstName);
                DateFormat formatter = new SimpleDateFormat("yyyy-mm-dd");
                user.setDateNaissance(formatter.parse(dateNaissance));
                user.setDateAdhesion(new Date());
                user.setLogin(login);
                user.setPwd(pwd);
                user.setAdresse(userAdress);
                
                // Persist user into DB via the utilisateurDAO service.
                utilisateurDao.persist(user);
                forwardStatement = "UserSpace.jsp";
                request.getSession().setAttribute("loggedUser",user.getLogin());
                // create panier instance
                Panier panier = new Panier();
//                utilisateurDao.merge(user);
                panier.setUtilisateur(user);
                IPanierDao panierDao = new ImplPanierDao();
                panierDao.merge(panier);
            }
            else
            {
                request.setAttribute("error", "Le nom d'utilisateur existe déjà");
            }
            request.getRequestDispatcher(forwardStatement).forward(request, response);
        } catch (Exception ex) {
            ex.printStackTrace();
            try {
                request.getRequestDispatcher(forwardStatement).forward(request, response);
            } catch (IOException ex1) {
                Logger.getLogger(CreateUserServlet.class.getName()).log(Level.SEVERE, null, ex1);
            }
        } 
        
    }
    
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
    
    /** Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
    
    /** Returns a short description of the servlet.
     */
    public String getServletInfo() {
        return "Short description";
    }
    // </editor-fold>
}
